<template>
    <div v-if="selectedPackage">
        <h3>SKU 选择</h3>
        <div v-for="(skuGroup, groupName) in selectedPackage.skus" :key="groupName">
            <label>{{ groupName }}：</label>
            <select v-model="selectedSkus[groupName]" @change="calculatePrice">
                <option v-for="(sku, skuKey) in skuGroup" :key="skuKey" :value="skuKey">
                    {{ sku.name }} (¥{{ sku.price }})
                </option>
            </select>
        </div>
    </div>
</template>

<script>
export default {
    props: {
        selectedPackage: {
            type: Object,
            default: null
        }
    },
    data() {
        return {
            selectedSkus: {}
        };
    },
    watch: {
        selectedPackage(newPackage) {
            if (newPackage) {
                const initialSkus = {};
                Object.keys(newPackage.skus).forEach(groupName => {
                    initialSkus[groupName] = Object.keys(newPackage.skus[groupName])[0];
                });
                this.selectedSkus = initialSkus;
            }
        }
    },
    methods: {
        calculatePrice() {
            let totalPrice = this.selectedPackage.price;
            Object.keys(this.selectedSkus).forEach(groupName => {
                const skuKey = this.selectedSkus[groupName];
                totalPrice += this.selectedPackage.skus[groupName][skuKey].price;
            });
            this.$emit('price-updated', totalPrice);
            this.$emit('sku-selected', this.selectedSkus);
        }
    }
};
</script>